<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import {computed, reactive, ref, shallowRef, onBeforeUnmount, watch} from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { AddOrUpdateInspectionCheckCommand, updateInspectionCheckApi } from "@/api/airport/inspection/inspectionCheck";


import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
// import { Boot } from '@wangeditor/editor'
// import attachmentModule from '@wangeditor/plugin-upload-attachment'
// Boot.registerModule(attachmentModule)

import "@wangeditor/editor/dist/css/style.css";
import {useInspectionCheckHook} from "@/views/airport/inspection/inspectionDetail/utils/hook";
import { useUserStoreHook } from "@/store/modules/user"; // 引入用户状态管理
import { getUsersByDeptIdApi } from '../inspectionList/utils/hook';
import {
  UserInfo,
  ApiResponse,
  assertApiResponse,
  editorConfig,
  mobileToolbarConfig,
} from "@/api/airport/inspection/inspection";


import { startInspectionApi, UpdateInspectionCheckCommand } from "@/api/airport/inspection/inspectionCheck";

interface Props {
  type: "add" | "update";
  modelValue: boolean;
  row?: {
    inspectionId: number;
    inspectionCheckId?: number;
    professional?: string;
    checkContent?: string;
    checkStandard?: string;
    complianceCriteria?: string;
    checkMethod?: string;
    companyBasis?: string;
    companyClause?: string;
    lawsBasis?: string;
    lawsClause?: string;
    baseCycle?: string;
    integrationSource?: string;
  };
  deptTree: any[]; // 定义 deptTree prop
}


const userList = ref<Array<{ id: number; name: string }>>([]);


const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

// 定义计算属性来安全地绑定表单字段
const professional = computed(() => props.row?.professional || '');
const checkContent = computed(() => props.row?.checkContent || '');
const checkStandard = computed(() => props.row?.checkStandard || '');
const complianceCriteria = computed(() => props.row?.complianceCriteria || '');
const checkMethod = computed(() => props.row?.checkMethod || '');
const companyBasis = computed(() => props.row?.companyBasis || '');
const companyClause = computed(() => props.row?.companyClause || '');
const lawsBasis = computed(() => props.row?.lawsBasis || '');
const lawsClause = computed(() => props.row?.lawsClause || '');
const baseCycle = computed(() => props.row?.baseCycle || '');
const integrationSource = computed(() => props.row?.integrationSource || '');

// 定义初始数据对象
const getInitialFormData = () => ({
  inspectionId: props.row?.inspectionId || 0,
  inspectionCheckId: props.row?.inspectionCheckId || 0,
  inspectionResult: undefined, // 符合1 不符合2 不适用3
  inspectionQuestion: undefined,
  dealType: undefined,
  dutyDeptId: undefined,
  curDealDeptId: undefined,
  tittle: undefined,
  safetyContent: undefined,
  inspectionUserId: undefined,
  inspector: undefined,
  discoveryPlace: undefined,
  reformRequirement: undefined,
  actionDeadline: undefined,
  correctiveDeadline: undefined,
});


// 创建响应式表单对象
const formData = reactive(getInitialFormData());

const formRef = ref<FormInstance>();
const loading = ref(false);
const userStore = useUserStoreHook();

// 检查结果选项
const inspectionResultOptions = [
  { label: "符合", value: "1" },
  { label: "不符合", value: "2" },
  { label: "不适用", value: "3" }
];

// 处理方式选项
const dealTypeOptions = [
  { label: "直接整改", value: "1" },
  { label: "建模后整改", value: "2" },
];

// --- 逻辑重构：使用 Computed 属性控制UI显隐 ---
const isNonCompliant = computed(() => formData.inspectionResult === '2');
const isNotApplicable = computed(() => formData.inspectionResult === '3');
const isDirectRectification = computed(() => formData.dealType === '1');
const isModelledRectification = computed(() => formData.dealType === '2');

// 控制各UI模块的显示
const showProblemDescription = computed(() => isNonCompliant.value || isNotApplicable.value);
const showNonCompliantFields = computed(() => isNonCompliant.value);
const showDirectRectificationFields = computed(() => isNonCompliant.value && isDirectRectification.value);
const showModelledRectificationFields = computed(() => isNonCompliant.value && isModelledRectification.value);

// 将部门树扁平化，用于搜索下拉框
const deptOptions = computed(() => {
  const flattenDept = (depts: any[]): { value: any; label: string }[] => {
    return depts.reduce((acc, dept) => {
      acc.push({ value: dept.value, label: dept.label });
      if (dept.children && dept.children.length) {
        acc.push(...flattenDept(dept.children));
      }
      return acc;
    }, [] as { value: any; label: string }[]);
  };
  return flattenDept(props.deptTree);
});


watch(
  () => formData.dutyDeptId,
  async (deptId) => {
    if (deptId) {
      const response = await getUsersByDeptIdApi(deptId);
      if (assertApiResponse(response) && response.code === 0) {
        userList.value = response.data.map((user) => ({
          id: user.userId,
          name: user.username
        }));
      } else {
        userList.value = [];
      }
    } else {
      userList.value = [];
    }
    // 当责任单位变化时，清空督察员，避免数据不一致
    formData.inspector = undefined;
  }
);

// 编辑器实例
const editorRef = shallowRef();

// 校验规则 (确保所有可见输入项都为必填)
const rules = reactive<FormRules>({
  inspectionResult: [{ required: true, message: '请选择检查结果', trigger: 'change' }],
  tittle: [{  required: true, message: '请输入标题', trigger: 'blur' }],
  dutyDeptId: [{ required: true, message: '请选择责任单位', trigger: 'change' }],
  curDealDeptId: [{ required: true, message: '请选择处理部门', trigger: 'change' }],
  dealType: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
  inspector: [{ required: true, message: '请选择督察员', trigger: 'change' }],
  reformRequirement: [{ required: true, message: "请输入整改要求", trigger: "blur" }],
  actionDeadline: [{ required: true, message: "请选择制定措施期限", trigger: "change" }],
  correctiveDeadline: [{ required: true, message: "请选择整改完成期限", trigger: "change" }],
  safetyContent: [{ required: true, message: "请详细描述安全信息", trigger: "blur" }],
  discoveryPlace: [{ required: true, message: "请输入发现地点", trigger: "blur" }],
  inspectionQuestion: [
    {
      required: true,
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (showProblemDescription.value && (!value || value.replace(/<[^>]*>?/gm, '').trim() === '')) {
          callback(new Error('请输入不符合理由与证据'));
        } else {
          callback();
        }
      }
    }
  ],
});

// 监听检查结果变化，只负责重置数据
const handleResultChange = (value: string) => {
  const inspectionId = formData.inspectionId;
  const inspectionCheckId = formData.inspectionCheckId;
  Object.assign(formData, getInitialFormData());
  formData.inspectionId = inspectionId;
  formData.inspectionCheckId = inspectionCheckId;
  formData.inspectionResult = value;
};

// 监听处理方式变化，只负责重置相关数据
const handleDealTypeChange = (value: string) => {
  formData.reformRequirement = undefined;
  formData.actionDeadline = undefined;
  formData.correctiveDeadline = undefined;
  formData.safetyContent = undefined;
  formData.discoveryPlace = undefined;
};

/**
 * 将 HTML 富文本内容编码为 Base64（UTF-8）
 */
function encodeHtmlToBase64(html: string): string {
  const utf8Bytes = new TextEncoder().encode(html);
  const binaryString = Array.from(utf8Bytes)
    .map(byte => String.fromCharCode(byte))
    .join("");
  return btoa(binaryString);
}

// 提交函数
const handleConfirm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    loading.value = true;
    formData.inspectionUserId = userStore.currentUserInfo?.userId;
    const submissionData = { ...formData };
    if (submissionData.inspectionQuestion) {
      submissionData.inspectionQuestion = encodeHtmlToBase64(submissionData.inspectionQuestion);
    }
    if (props.type === "update") {
      await startInspectionApi(submissionData as UpdateInspectionCheckCommand);
    }
    ElMessage.success("提交成功");
    visible.value = false;
    emits("success");
  } catch (e) {
    console.error(e);
    ElMessage.error((e as Error)?.message || "请完成必填项");
  } finally {
    loading.value = false;
  }
};

// 弹窗打开时，重置所有状态到初始
function handleOpened() {
  Object.assign(formData, getInitialFormData());
  if (formRef.value) {
    formRef.value.clearValidate();
  }
  userList.value = [];
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor;
};
</script>

<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    :title="'在线检查'"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    @opened="handleOpened"
    width="100%"
  >
    <el-form :model="formData" label-position="top" ref="formRef" :rules="rules">
      <div class="readonly-details">
        <div class="detail-item">
          <strong>专业：</strong>{{ professional }}
        </div>
        <div class="detail-item">
          <strong>检查内容：</strong>{{ checkContent }}
        </div>
        <div class="detail-item">
          <strong>检查方式：</strong>{{ checkMethod }}
        </div>
        <div class="detail-item">
          <strong>公司依据：</strong>{{ companyBasis }}
        </div>
        <div class="detail-item">
          <strong>公司条款：</strong>{{ companyClause }}
        </div>
        <div class="detail-item">
          <strong>基础周期：</strong>{{ baseCycle }}
        </div>
        <div class="detail-item">
          <strong>融合来源：</strong>{{ integrationSource }}
        </div>
        <div class="detail-item">
          <strong>法律法规依据：</strong>{{ lawsBasis }}
        </div>
        <div class="detail-item">
          <strong>法律法规条款：</strong>{{ lawsClause }}
        </div>
        <div class="detail-item">
          <strong>检查标准：</strong>{{ checkStandard }}
        </div>
        <div class="detail-item">
          <strong>符合性判定标准：</strong>{{ complianceCriteria }}
        </div>
      </div>
      <el-form-item prop="inspectionResult" label="检查结果：">
        <el-radio-group v-model="formData.inspectionResult" @change="handleResultChange">
          <el-radio
            v-for="option in inspectionResultOptions"
            :key="option.value"
            :label="option.value"
          >
            {{ option.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="showNonCompliantFields" prop="tittle" label="标题（简述问题内容）：">
        <el-input v-model="formData.tittle" placeholder="请输入标题" />
      </el-form-item>

      <el-form-item v-if="showProblemDescription" prop="inspectionQuestion" label="不符合理由与证据：">
        <div style="border: 1px solid #ccc; width: 100%;">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="mobileToolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 250px; overflow-y: hidden;"
            v-model="formData.inspectionQuestion"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>

      <template v-if="showNonCompliantFields">
        <el-form-item prop="dutyDeptId" label="责任单位：">
          <el-select
            v-model="formData.dutyDeptId"
            filterable
            clearable
            placeholder="请搜索并选择责任单位"
            style="width: 100%;"
          >
            <el-option
              v-for="dept in deptOptions"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="curDealDeptId" label="处理部门：">
          <el-select
            v-model="formData.curDealDeptId"
            filterable
            clearable
            placeholder="请搜索并选择处理部门"
            style="width: 100%;"
          >
            <el-option
              v-for="dept in deptOptions"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="督察员：" prop="inspector">
          <el-radio-group v-model="formData.inspector">
            <el-radio v-for="user in userList" :key="user.id" :label="user.name">
              {{ user.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="dealType" label="处理方式：">
          <el-radio-group v-model="formData.dealType" @change="handleDealTypeChange">
            <el-radio
              v-for="option in dealTypeOptions"
              :key="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </template>

      <template v-if="showDirectRectificationFields">
        <el-form-item label="整改要求：" prop="reformRequirement">
          <el-input
            v-model="formData.reformRequirement"
            type="textarea"
            :rows="4"
            placeholder="请输入整改要求"
          />
        </el-form-item>
        <el-form-item label="制定措施期限：" prop="actionDeadline">
          <el-date-picker
            v-model="formData.actionDeadline"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择制定措施期限"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="整改完成期限：" prop="correctiveDeadline">
          <el-date-picker
            v-model="formData.correctiveDeadline"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择整改完成期限"
            style="width: 100%;"
          />
        </el-form-item>
      </template>

      <template v-if="showModelledRectificationFields">
        <el-form-item prop="safetyContent" label="安全信息描述：">
          <el-input type="textarea" :rows="4" v-model="formData.safetyContent"
                    placeholder="请详细描述存在的安全危险隐患的内容"
          />
        </el-form-item>
        <el-form-item prop="discoveryPlace" label="发现地点：">
          <el-input v-model="formData.discoveryPlace" placeholder="请输入发现地点" />
        </el-form-item>
      </template>

      <div style="height: 20px"></div>
    </el-form>
  </v-dialog>
</template>

<style scoped lang="scss">
.dialog-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 22px;
}

.readonly-details {
  margin-bottom: 22px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #dcdfe6;
}

.detail-item {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  word-break: break-word; /* Ensures long text wraps correctly */
  margin-bottom: 12px;
  &:last-child {
    margin-bottom: 0;
  }
}

.detail-item strong {
  font-weight: bold;
  color: #303133;
}

.detail-value {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  word-break: break-word;
}

:deep(.el-form-item__label) {
  font-weight: bold !important;
  color: #303133;
}
</style>
